package com.zxb.core.common.service.impl;

import cn.hutool.core.util.StrUtil;
import com.zxb.core.common.service.MinioService;
import com.zxb.core.util.IdUtil;
import io.minio.*;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author Zxb
 */
@Service
@RequiredArgsConstructor
public class MinioServiceImpl implements MinioService {

    private final MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    public String handlePath(String path) {
        if (StrUtil.isBlank(path)) {
            return null;
        }
        String prefix = "/" + bucketName + "/";
        return path.substring(prefix.length());
    }

    @Override
    @SneakyThrows
    public void del(String path) {
        path = handlePath(path);
        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(path)
                        .build()
        );
    }

    @Override
    public boolean exist(String path) {
        path = handlePath(path);
        boolean exist = true;
        try {
            minioClient.statObject(
                    StatObjectArgs.builder()
                            .bucket(bucketName)
                            .object(path)
                            .build()
            );
        } catch (Exception e) {
            exist = false;
        }
        return exist;
    }

    @Override
    @SneakyThrows
    public String upload(MultipartFile f) {
        String name = f.getOriginalFilename();
        //后缀
        String suffix = (StrUtil.isNotBlank(name) && name.contains(".")) ? name.substring(name.lastIndexOf(".")) : "";
        //新文件名
        String fileName = IdUtil.nextIdStr() + suffix;
        //日期
        String day = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(day + "/" + fileName)
                .stream(f.getInputStream(), f.getSize(), -1)
                .contentType(f.getContentType())
                .build());
        return "/" + bucketName + "/" + day + "/" + fileName;
    }

    @Override
    @SneakyThrows
    public InputStream getObject(String path) {
        path = handlePath(path);
        return minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(path)
                .build());
    }
}
